

package com.hazelcast.internal.serialization.impl.defaultserializers;

import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;

import java.io.IOException;
import java.util.Collection;

/**
 * The {@link Collection} serializer
 */
abstract class AbstractCollectionStreamSerializer<CollectionType extends Collection<?>> implements StreamSerializer<CollectionType> {

    @Override
    public void write(ObjectDataOutput out, CollectionType collection) throws IOException {
        int size = collection.size();
        out.writeInt(size);
        for (Object o : collection) {
            out.writeObject(o);
        }
    }

    CollectionType deserializeEntries(ObjectDataInput in, int size, CollectionType collection) throws IOException {
        deserializeEntriesInto(in, size, collection);
        return collection;
    }

    void deserializeEntriesInto(ObjectDataInput in, int size, Collection<?> collection) throws IOException {
        for (int i = 0; i < size; i++) {
            collection.add(in.readObject());
        }
    }

}
